﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ControlFace;
using Etalk.Library;
using System.Threading;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace EtalkClient
{
    public partial class ClientMain : ControlFace.IMForm
    {
        ControlFace.User userOwner, user_小强;
        ControlFace.Group groupFriend;
        private System.Timers.Timer myTimer;
        public ClientMain()
        {
            InitializeComponent();
        }
        private void ClientMain_Load(object sender, EventArgs e)
        {

            Login login = new Login();
            login.ShowDialog();
            if (login.DialogResult != DialogResult.OK)
            {
                Application.Exit();
                return;
            }

            userOwner = new ControlFace.User(ClientUser.LoginedUser.ID, ClientUser.LoginedUser.LoginName, ClientUser.LoginedUser.UserName, ControlFace.UserSex.Male, Properties.Resources.head, "", "");
            userOwner.State = ControlFace.OnlineState.Online;
            ControlFace.Common.My = userOwner;
            lblName.Text = ClientUser.LoginedUser.UserName;
            lblCity.Text = ClientUser.LoginedUser.City;
           
            groupFriend = new ControlFace.Group("0", "旅客");
           
            ControlFace.SlidingBar bar  = new ControlFace.SlidingBar("购票用户");
            bar.AddGroup(groupFriend);
            //bar.AddGroup(new ControlFace.Group("1223", "陌生人"));
            //bar.AddGroup(new ControlFace.Group("4354", "黑名单"));
            base.CloseBoxClick += new EventHandler(ClientMain_CloseBoxClick);
            base.MinimizeBoxClick += new EventHandler(ClientMain_MinimizeBoxClick);
            groupFriend.Users.UserCountChanged +=new EventHandler(Users_UserCountChanged);

            ControlFace.SlidingBarContainer barContainer =
                new ControlFace.SlidingBarContainer(bar,
                //    new ControlFace.SlidingBar("通讯录"),
                //    new ControlFace.SlidingBar("QQ群"),
                    new ControlFace.SlidingBar("最近联系人"));

            ControlFace.Tab tabQQ = new ControlFace.Tab(Properties.Resources.Tab_User, "Easydp用户", barContainer);
            this.tabContainer.Tabs.Add(tabQQ);
            LoadUser();

            Thread thread = new Thread(new ThreadStart(ReceiveContent));
            thread.Start();
            myTimer = new System.Timers.Timer(1000);
            myTimer.Elapsed +=new System.Timers.ElapsedEventHandler(myTimer_Elapsed);
            myTimer.Enabled = true; 

        }

        //删除用户
        private void user_DeleteUserHandler(object sender, EventArgs e)
        {
            if (MessageBox.Show("确认删除此用户", "删除用户", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
            {
                User userObj = (User)sender;
                groupFriend.Users.Remove(userObj);
                Common.AllUsers.Remove(userObj);
            }
        }
        private void Talk_ShowTalk(object sender, EventArgs e)
        {
            ControlFace.User userObj = (ControlFace.User)sender;

            foreach (Form item in Application.OpenForms)
            {
                if (item.Tag == userObj.UserName)
                {
                    item.Focus();
                    return;
                }
            }
            Talk talkFrom = new Talk(userObj);
            talkFrom.Tag = userObj.UserName;
            talkFrom.Show();
        }

        private void ReceiveContent()
        {
            bool flag = true;
            while (flag)
            {
                byte[] buffer = new byte[512];
                try
                {

                    if (!Client.ClientConn.Sock.Connected)
                        Client.ClientConn.Sock.Close();
                    Client.ClientConn.Sock.Receive(buffer);
                }
                catch (SocketException ex)
                {
                    // MessageBox.Show(ex.Message);
                    if (Client.ClientConn.Sock != null)
                    {
                        Client.ClientConn.Sock.Close();
                        Client.ClientConn.Host = null;
                    }
                    break;
                }
                catch (Exception exs)
                {

                }
                string msgData = System.Text.Encoding.UTF8.GetString(buffer).TrimEnd(new char[] { '\0' });
                string[] arrData = msgData.Split(new char[] { '|' });
                if (arrData.Length < 1)
                    return;
                if (arrData[0].ToString().ToUpper() == "PRIV")
                {
                    string key = arrData[1].ToString();//聊天对方ID
                    ControlFace.User user = BindUser(key);
                    user.State = OnlineState.Online;
                   user.Messages.Add(DateTime.Now, arrData[arrData.Length-1].ToString());
                    
                   foreach (Form item in Application.OpenForms)
                   {
                       if (item.Tag == user.UserName)
                       {
                           item.Invoke(new EventHandler(delegate(object sender,EventArgs e){
                               ((Talk)item).Message_Load(null, null);
                                 item.Focus();
                               }));
                           continue;
                       }
                   }
                }                
                else if (arrData[0].ToString().ToUpper() == "GONE")
                {
                    string promptingMsg = "用户 {0} 已经离开, 是否删除该用户?";
                    if (MessageBox.Show(string.Format(promptingMsg, arrData[1]), "用户已经离开", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                    {
                        User itemObj = groupFriend.Users.Find(u => u != null && u.UserID.ToUpper() == arrData[1].ToString().ToUpper());
                        groupFriend.Users.Remove(itemObj);
                        ControlFace.Common.AllUsers.Remove(itemObj);

                        foreach (Form item in Application.OpenForms)
                        {
                            if (item.Tag !=null && item.Tag.ToString()  == arrData[1].ToString())
                            {
                                item.Invoke(new EventHandler(delegate(object sender, EventArgs e)
                                {
                                    item.Close();
                                }));
                                break;
                            }
                        }
                                            
                    }
                }
            }
        }
        private ControlFace.User BindUser(string key)
        {
            //查看是否存在
            foreach (ControlFace.User item in ControlFace.Common.AllUsers)
            {
                if (item.UserID == key)
                {
                    return item;
                }
            }
            ControlFace.User user  = new User(key,key, "a", UserSex.Male, null, "a", "a");
            user.ShowTalk += new EventHandler(Talk_ShowTalk);
            user.DeleteUserHandler += new EventHandler(user_DeleteUserHandler);
            groupFriend.Users.Add(user);
            ControlFace.Common.AllUsers.Add(user);
            return user;
        }

        #region 序列化处理
        //保存到序列化
        private void Users_UserCountChanged(object sender,EventArgs e)
        {
            ActionUsers obj = new ActionUsers();
            foreach (User item in groupFriend.Users)
            {
                obj.Add(new ActionUser(item.UserID, item.UserName, item.Underwrite,item.Sex,item.Head,item.Mobile, item.Email));
            }
            BinaryFormatter formatter = new BinaryFormatter();
            Stream stream = new FileStream("ActionUsers.bin", FileMode.Create,
            FileAccess.Write, FileShare.None);
            formatter.Serialize(stream, obj);
            stream.Close();
        }

        private void LoadUser()
        {
            try
            {
                BinaryFormatter formatter = new BinaryFormatter();
                Stream stream = new FileStream("ActionUsers.bin", FileMode.Open,
                FileAccess.Read, FileShare.Read);
                ActionUsers obj = (ActionUsers)formatter.Deserialize(stream);
                stream.Close();
                foreach (ActionUser item in obj)
                {
                    User userObj = new User(item.UserID, item.UserName, item.Underwrite, item.Sex, item.Head, item.Mobile, item.Email);
                    userObj.DeleteUserHandler+=new EventHandler(user_DeleteUserHandler);
                    userObj.ShowTalk += new EventHandler(Talk_ShowTalk);
                    ControlFace.Common.AllUsers.Add(userObj);
                    groupFriend.Users.Add(userObj);
                }
            }
            catch (Exception ex)
            {

            }
        }

        #endregion

        #region 窗口Action

        Point point = new Point();
        private void notifyIcon1_Click(object sender, EventArgs e)
        {
            this.Visible = true;
            this.Location = point;
            this.WindowState = FormWindowState.Normal;
           // this.StartPosition = FormStartPosition.Manual;
            this.notifyIcon1.Visible = false;
            
        }

        private void ClientMain_MinimizeBoxClick(object sender, EventArgs e)
        {
            point.X = this.Location.X;
            point.Y = this.Location.Y;
            this.WindowState = FormWindowState.Minimized;
            this.Hide();
            this.notifyIcon1.Visible = true;
        }

        private void ClientMain_CloseBoxClick(object sender, EventArgs e)
        {
            //关闭From事件
            if (Client.ClientConn.Sock != null)
            {
                Client.ClientConn.Sock.Close();
                Client.ClientConn.Host = null;
            }
            notifyIcon1.Visible = false;
            Application.Exit();
        }

        #endregion

        private void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
           

            if (!Client.ClientConn.Sock.Connected)
            {
                this.Invoke(new EventHandler(delegate(object s, EventArgs ea)
                {
                txtStatus.Text = "与服务器断开;请重新登录..";
                }));
                myTimer.Enabled = false;
            }
            else
            {
                this.Invoke(new EventHandler(delegate(object s, EventArgs ea)
                                {
                txtStatus.Text = "连接正常";
                                }));

            }

            //AllSocket.Add(acceptSock);
        }
    }
}